package com.usian.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.yygh.cmn.listener.DictListener;
import com.usian.yygh.cmn.mapper.DictMapper;
import com.usian.yygh.cmn.service.DictService;
import com.usian.yygh.model.cmn.Dict;
import com.usian.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:WGG
 * @Date 2022年12月30日 9:51
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据数据id查询子数据列表
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
        List<Dict> list = list(Wrappers.<Dict>lambdaQuery().eq(Dict::getParentId, id));
        for (Dict dict : list) {
            Long isChild = dict.getId();
            boolean children = isChildren(isChild);
            dict.setHasChildren(children);
        }
        return list;
    }

    /**
     * 数据字典导出实现
     * @param response
     */
    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //查询所有数据
            List<Dict> list = list();
            //将dict数据转存到dictEeVo中
            ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
            for (Dict dict : list) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVos.add(dictEeVo);
            }
            //调用方法进行写操作
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet().doWrite(dictEeVos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导入数据字典
     * @param file
     */
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据dictCode和value查询名称
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getDictName(String dictCode, String value) {
        //判断dictCode是否为空
        if (StringUtils.isEmpty(dictCode)){
            //根据value查询名称
            Dict dict = this.getOne(Wrappers.<Dict>lambdaQuery().eq(Dict::getValue, value));
            return dict.getName();
        }else {
            //根据dictCode和value查询名称
            //1.根据dictCode查询parent_id
            Dict codeDict = this.getOne(Wrappers.<Dict>lambdaQuery().eq(Dict::getDictCode, dictCode));
            //2.根据parent_id和value查询名称
            Dict dict = this.getOne(Wrappers.<Dict>lambdaQuery()
                    .eq(Dict::getParentId, codeDict.getId())
                    .eq(Dict::getValue, value));
            return dict.getName();
        }
    }

    /**
     *根据dictCode获取下级节点
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> getByDictCode(String dictCode) {
        //获取省级id
        Dict dict = this.getOne(Wrappers.<Dict>lambdaQuery().eq(Dict::getDictCode, dictCode));
        //根据省级id查询所有省
        List<Dict> list = this.list(Wrappers.<Dict>lambdaQuery().eq(Dict::getParentId, dict.getId()));
        return list;
    }

    /**
     * 判断id下面是否有子节点
     * @param id
     * @return
     */
    private boolean isChildren(Long id){
        int count = this.count(Wrappers.<Dict>lambdaQuery().eq(Dict::getParentId, id));
        return count>0;
    }
}
